<?php

defined('SYSPATH') or die('Access error!');

/**
 * 操作配置文件
 */
class Config
{

    protected static $_instance;

    public static function instance()
    {
        if (self::$_instance === NULL)
        {
            self::$_instance = new Config();
        }
        return self::$_instance;
    }

    protected $_readers = array();

    public function attach(Config_Reader $reader, $first = TRUE)
    {
        if ($first === TRUE)
        {
            array_unshift($this->_readers, $reader);
        }
        else
        {
            $this->_readers[] = $reader;
        }

        return $this;
    }

    public function detach(Config_Reader $reader)
    {
        if (($key = array_search($reader, $this->_readers)) !== FALSE)
        {
            unset($this->_readers[$key]);
        }

        return $this;
    }

    public function load($group)
    {
        foreach ($this->_readers as $reader)
        {
            if ($config = $reader->load($group))
            {
                return $config;
            }
        }
        reset($this->_readers);

        if (!is_object($config = current($this->_readers)))
        {
            throw new Core_Exception('No configuration readers attached');
        }

        return $config->load($group, array());
    }

    public function copy($group)
    {
        $config = $this->load($group);
        foreach ($this->_readers as $reader)
        {
            if ($config instanceof $reader)
            {
                continue;
            }

            $object = $reader->load($group, array());

            foreach ($config as $key => $value)
            {
                $object->offsetSet($key, $value);
            }
        }

        return $this;
    }

}